﻿using System;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraCharts;

namespace TaxiDispatchClient
{
    public partial class TaxiStateStatisticsReportForm : DevExpress.XtraEditors.XtraForm
    {
        public TaxiStateStatisticsReportForm()
        {
            InitializeComponent();
            BindCombox();
            dateEdit1.DateTime = DateTime.Now;

            //chartControl1.Series[0].ArgumentScaleType = ScaleType.Qualitative;
            //chartControl1.Series[0].ValueScaleType = ScaleType.Numerical;
            //chartControl1.Series[0].PointOptions.PointView = PointView.ArgumentAndValues;
            //chartControl1.Series[0].PointOptions.ValueNumericOptions.Format = NumericFormat.Percent;

        }

        private string _title = "";
        private int _dtType = 0;
        private string _ds1Title = "";
        private Thread thread;
        private void btn_getResult_Click(object sender, EventArgs e)
        {
            if (CheckIsValid())
            {
                chartControl1.Titles[0].Text = "统计中...";
                chartControl2.Titles[0].Text = "统计中...";
                thread = new Thread(GetResult);
                thread.IsBackground = true;
                thread.Start();
            }
        }

        private bool CheckIsValid()
        {
            if (dateEdit1.Text == "")
            {
                XtraMessageBox.Show("请选择查询日期！");
                return false;
            }
            int intObject = combox_taxi.SelectedIndex + 1;
            if (intObject == 1)
            {
                if (textEdit_taxi.Text.Trim() == "")
                {
                    XtraMessageBox.Show("请选择想要查询的出租车！");
                    textEdit_taxi.Focus();
                    return false;
                }
            }
            else if (intObject == 2)
            {
                //if (combox_taxiGroups.SelectedIndex == -1)
                //{
                //    XtraMessageBox.Show("请选择想要查询的出租车分组！");
                //    combox_taxiGroups.Focus();
                //    return false;
                //}
            }
            return true;
        }

        private void GetResult()
        {
            #region 检验查询条件 并得出结果

            try
            {
                DateTime date = dateEdit1.DateTime;
                int intObject = combox_taxi.SelectedIndex + 1;
                string objValue = "";
                if (intObject == 1)
                {
                    objValue = textEdit_taxi.Text.Trim();
                    _ds1Title = "该车";
                }
                else if (intObject == 2)
                {
                    //_ds1Title = "该分组出租车";
                    //objValue = combox_taxiGroups.Properties.Items[combox_taxiGroups.SelectedIndex].Value.ToString();

                    intObject = 3;
                    objValue = "";
                    _ds1Title = "所有出租车";
                }
                else if (intObject == 3)
                {
                    objValue = "";
                    _ds1Title = "所有出租车";
                }
                int intDateType = combox_dateType.SelectedIndex + 2;
                _dtType = intDateType;
                StringBuilder sql = new StringBuilder();
                DataSet ds1 = new DataSet();
                DataSet ds2 = new DataSet();
                if (intDateType == 2) //按天统计
                {
                    _ds1Title += date.Date.ToString("yyyy-MM-dd") + "总载客率、空载率";
                    _title = date.Date.ToString("yyyy-MM-dd") + " 当天载客率、空载率统计情况";
                    sql.Append("UpdateTime Between '");
                    sql.Append(date.Date.ToString("yyyy-MM-dd"));
                    sql.Append("' and '");
                    sql.Append(date.Date.ToString("yyyy-MM-dd"));
                    sql.Append(" 23:59:59'");
                }
                else if (intDateType == 3) //按月统计
                {
                    _ds1Title += date.Date.ToString("yyyy年MM月") + "总载客率、空载率";
                    _title = date.ToString("yyyy年MM月") + " 每日载客率、空载率统计情况";
                    DateTime firstDay = new DateTime(date.Year, date.Month, 1);
                    DateTime lastDay = firstDay.AddMonths(1).AddDays(-1);
                    sql.Append("UpdateTime Between '");
                    sql.Append(firstDay.ToString("yyyy-MM-dd"));
                    sql.Append("' and '");
                    sql.Append(lastDay.ToString("yyyy-MM-dd"));
                    sql.Append(" 23:59:59");
                    sql.Append("'");
                }
                else if (intDateType == 4) //按年统计
                {
                    _ds1Title += date.Date.ToString("yyyy年") + "总载客率、空载率";
                    _title = date.ToString("yyyy年") + " 每月载客率、空载率统计情况";
                    DateTime firstDay = new DateTime(date.Year, 1, 1);
                    DateTime lastDay = new DateTime(date.Year, 12, 31);
                    sql.Append("UpdateTime Between '");
                    sql.Append(firstDay.ToString("yyyy-MM-dd"));
                    sql.Append("' and '");
                    sql.Append(lastDay.ToString("yyyy-MM-dd"));
                    sql.Append(" 23:59:59");
                    sql.Append("'");
                }

                if (MainForm.MyUserInfo.CompanyName!=Service.PowerConfig.MainCompanyName)
                {
                    sql.Append(" and CompanyName = '");
                    sql.Append(MainForm.MyUserInfo.CompanyName);
                    sql.Append("'");
                }


                Invoke(new MethodInvoker(() => { btn_getResult.Enabled = false; }));
                try
                {
                    ds1 = MainForm.PositionService.TaxiGpsHistoryGetStatisResult(
                        intObject, objValue, intDateType, sql.ToString());
                    ds2 = MainForm.PositionService.TaxiGpsHistoryGetStatisResult(
                        intObject, objValue, intDateType - 1, sql.ToString());

                }
                catch (Exception ex)
                {
                    if (!ex.Message.Contains("正在中止线程"))
                    {
                        Common.CommonRoutine.HandlingExceptions(ex, true);
                        Invoke(new MethodInvoker(() => { btn_getResult.Enabled = true; }));
                    }
                    return;
                }
            #endregion

                Invoke(new MethodInvoker(() =>
                {
                    chartControl1.Series.Clear();
                    chartControl2.DataSource = null;
                }));
                //chartControl1.Series.Clear();
                Series series = new Series("饼图统计", ViewType.Pie3D);
                //chartControl1.Series.Add(series);
                //chartControl1.Series[0].Points.Clear();

                //总结果报表chartControl1赋值
                double carrypert = 0;
                double nopert = 0;
                double otherpert = 0;
                try
                {

                    if (ds1 != null && ds1.Tables.Count == 1 && ds1.Tables[0].Rows.Count > 0)
                    {
                        carrypert = double.Parse(ds1.Tables[0].Rows[0]["CarryPsgPerts"].ToString());
                        nopert = double.Parse(ds1.Tables[0].Rows[0]["NoPsgPerts"].ToString());
                        otherpert = double.Parse(ds1.Tables[0].Rows[0]["OtherPerts"].ToString());
                        Invoke(new MethodInvoker(() =>
                        {
                            chartControl1.Titles[0].Text = _ds1Title;
                        }));
                        //if (chartControl1.Series[0].Points.Count == 0)
                        //{
                        SeriesPoint seriesPoint = new SeriesPoint("载客率", carrypert);
                        series.Points.Add(seriesPoint);
                        seriesPoint = new SeriesPoint("空载率", nopert);
                        series.Points.Add(seriesPoint);
                        seriesPoint = new SeriesPoint("其他", otherpert);
                        series.Points.Add(seriesPoint);
                        //}
                        //else
                        //{
                        //    chartControl1.Series[0].Points[0].Values = new double[] { carrypert };
                        //    chartControl1.Series[0].Points[1].Values = new double[] { nopert };
                        //    chartControl1.Series[0].Points[2].Values = new double[] { otherpert };
                        //}
                        // BeginInvoke(new MethodInvoker(() => { chartControl1.Show(); }));
                    }

                    Invoke(new MethodInvoker(() => { chartControl1.Series.Add(series); }));

                    //详细报表chartControl2赋值
                    if (ds2 != null && ds2.Tables.Count == 1)
                    {
                        Invoke(new MethodInvoker(() =>
                        {
                            chartControl2.DataSource = ds2.Tables[0];
                            chartControl2.Titles[0].Text = _title;
                            chartControl2.Series[0].ArgumentDataMember = "DT";
                            chartControl2.Series[0].ValueDataMembers.AddRange(new string[] { "CarryPsgPerts" });
                            chartControl2.Series[1].ArgumentDataMember = "DT";
                            chartControl2.Series[1].ValueDataMembers.AddRange(new string[] { "NoPsgPerts" });
                            chartControl2.Series[2].ArgumentDataMember = "DT";
                            chartControl2.Series[2].ValueDataMembers.AddRange(new string[] { "OtherPerts" });
                        }));
                    }
                }
                catch (Exception ex)
                {
                    Common.CommonRoutine.HandlingExceptions(ex);
                }

                BeginInvoke(new MethodInvoker(() => { btn_getResult.Enabled = true; }));
            }
            catch (Exception ex)
            {

                Common.CommonRoutine.HandlingExceptions(ex);
                Console.WriteLine(ex);
            }

        }




        //绑定需要绑定数据的下拉框
        private void BindCombox()
        {
            try
            {
                //绑定出租车分组
                //DataSet ds = MainForm.PositionService.TaxiGroupGetList("");
                //if (ds != null && ds.Tables[0].Rows.Count > 0)
                //{
                //    foreach (DataRow row in ds.Tables[0].Rows)
                //    {
                //        ImageComboBoxItem item = new ImageComboBoxItem();
                //        item.Description = row["TaxiGroup"].ToString();
                //        item.Value = row["id"].ToString();
                //        combox_taxiGroups.Properties.Items.Add(item);
                //    }
                //}
            }
            catch (Exception ex)
            {
                Common.CommonRoutine.HandlingExceptions(ex);
            }
        }

        //出租车对象选择
        private void combox_taxi_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (combox_taxi.SelectedIndex)
            {
                case 0:
                    lb_object.Text = "出租车号码：";
                    lb_object.Visible = true;
                    textEdit_taxi.Location = combox_taxiGroups.Location;
                    textEdit_taxi.Text = "";
                    textEdit_taxi.Visible = true;
                    btn_selectTaxi.Visible = true;
                    combox_taxiGroups.Visible = false;
                    break;
                //case 1:
                //    lb_object.Text = "选择分组：";
                //    lb_object.Visible = true;
                //    combox_taxiGroups.Visible = true;
                //    textEdit_taxi.Visible = false;
                //    btn_selectTaxi.Visible = false;
                //    break;
                case 1:
                    lb_object.Visible = false;
                    combox_taxiGroups.Visible = false;
                    textEdit_taxi.Visible = false;
                    btn_selectTaxi.Visible = false;
                    break;
            }

        }

        //选着单个出租车
        private void btn_selectTaxi_Click(object sender, EventArgs e)
        {
            DriverInfoForm driverInfoForm = new DriverInfoForm();
            driverInfoForm.ShowDialog();
            if (driverInfoForm.gridView1.FocusedRowHandle >= 0)
            {
                DataRow row = driverInfoForm.gridView1.GetDataRow(driverInfoForm.gridView1.FocusedRowHandle);
                textEdit_taxi.Text = row["phoneNumber"].ToString();
                //label_driver.Text = row["Name"].ToString();                               
            }
        }

        #region 窗体控件效果
        Point _mouseOff;
        bool _leftFlag;
        private void Form_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseOff = new Point(-e.X, -e.Y);
                _leftFlag = true;
            }
        }

        private void Form_MouseMove(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(_mouseOff.X, _mouseOff.Y);
                Location = mouseSet;
            }
        }

        private void Form_MouseUp(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                _leftFlag = false;
            }
        }

        private void pictureEdit_exit_MouseHover(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexit;
            Cursor = Cursors.Hand;
        }

        private void pictureEdit_exit_MouseLeave(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexitPressDown;

            Cursor = Cursors.Arrow;

        }
        private void btn_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
        }

        private void btn_MouseLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Arrow;
        }

        private void pictureEdit_exit_Click(object sender, EventArgs e)
        {
            Close();
        }
        private void TaxiStateStatisticsReportForm_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Close();
            }
        }

        #endregion

        private void btn_seeAllTaxiStati_Click(object sender, EventArgs e)
        {
            TaxiStateStatisticsForm taxiStateStatistics = new TaxiStateStatisticsForm();
            taxiStateStatistics.ShowDialog();
        }

        private void TaxiStateStatisticsReportForm_Load(object sender, EventArgs e)
        {
            btn_getResult_Click(null, null);
        }

        private void TaxiStateStatisticsReportForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (thread != null)
            {
                thread.Abort();
            }
        }

    }
}